package com.zj.web.config;

import cn.zj.smart.util.bean.ApiResult;
import cn.zj.smart.util.exception.AuthException;
import cn.zj.smart.util.exception.ServiceException;
import cn.zj.smart.util.exception.WarnException;
import com.zj.web.config.util.I18nUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 全局异常处理
     */
    @ExceptionHandler
    public ApiResult handleException(HttpServletRequest request, HttpServletResponse response, final Exception e) {
        log.warn("Error path is [{}]", request.getRequestURI());
        e.printStackTrace();
        if (e instanceof AuthException) {
            return ApiResult.auth(e.getMessage());
        }else if (e instanceof ServiceException) {
            return ApiResult.error(e.getMessage());
        } else if (e instanceof WarnException) {
            // TODO: 2020/3/19 获取当前语言
            return ApiResult.warn(I18nUtil.getMessage(e.getMessage()));
        } else {//其它异常
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return ApiResult.error(e.getMessage());
        }
    }

}